// src/utils/http.ts
import axios, {
    type AxiosInstance,
    type AxiosRequestConfig,
    type AxiosResponse,
    type InternalAxiosRequestConfig,
    type CancelTokenSource
  } from 'axios'
  import { message } from 'antd'
  
  // 基础响应类型
  export interface ApiResponse<T = any> {
    code: number
    data: T
    message?: string
    success: boolean
  }
  
  // 扩展请求配置
  interface RequestConfig extends AxiosRequestConfig {
    silent?: boolean // 是否静默模式（不显示错误提示）
    useLoading?: boolean // 是否使用loading
  }
  
  // 创建axios实例
  class HttpRequest {
    private instance: AxiosInstance
    private pendingRequests: Map<string, CancelTokenSource> = new Map()
    private messageApi = message
  
    constructor(baseURL: string) {
      this.instance = axios.create({
        baseURL,
        timeout: 10000,
        headers: { 'Content-Type': 'application/json' }
      })
  
      // 请求拦截器
      this.instance.interceptors.request.use(
        (config: InternalAxiosRequestConfig) => {
          this.removePending(config)
          this.addPending(config)
          this.handleRequestLoading(config, true)
          const token = localStorage.getItem('token')
          if (token) {
            config.headers.Authorization = `Bearer ${token}`
          }
          return config
        },
        error => Promise.reject(error)
      )
  
      // 响应拦截器
      this.instance.interceptors.response.use(
        (response: AxiosResponse) => {
          this.removePending(response.config)
          this.handleRequestLoading(response.config, false)
          return this.handleResponse(response)
        },
        error => {
          this.handleRequestLoading(error.config, false)
          this.removePending(error.config)
          return this.handleError(error)
        }
      )
    }
  
    // 处理响应
    private handleResponse<T>(response: AxiosResponse<ApiResponse<T>>) {
      const res = response.data
      if (res.code === 401) {
        this.handleUnauthorized()
        return Promise.reject(res)
      }
      if (!res.success) {
        // if (!response.config.silent) {
        //   this.messageApi.error(res.message || '请求失败')
        // }
        return Promise.reject(res)
      }
      return res.data
    }
  
    // 处理错误
    private handleError(error: any) {
      if (!axios.isCancel(error)) {
        const errorMessage = error.response?.data?.message || 
          error.message || 
          '请求错误'
        if (!error.config?.silent) {
          this.messageApi.error(errorMessage)
        }
      }
      return Promise.reject(error)
    }
  
    // 处理未授权
    private handleUnauthorized() {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
  
    // 处理loading
    private handleRequestLoading(config: any, show: boolean) {
      if (config.useLoading) {
        // 这里可以接入全局loading状态管理
        console.log('Loading:', show)
      }
    }
  
    // 添加请求到pending队列
    private addPending(config: InternalAxiosRequestConfig) {
      const source = axios.CancelToken.source()
      const key = this.getRequestKey(config)
      config.cancelToken = source.token
      this.pendingRequests.set(key, source)
    }
  
    // 移除pending请求
    private removePending(config: InternalAxiosRequestConfig) {
      const key = this.getRequestKey(config)
      if (this.pendingRequests.has(key)) {
        const source = this.pendingRequests.get(key)
        source?.cancel('重复请求已取消')
        this.pendingRequests.delete(key)
      }
    }
  
    // 生成请求唯一key
    private getRequestKey(config: InternalAxiosRequestConfig) {
      return [config.method, config.url, JSON.stringify(config.params)].join('&')
    }
  
    // 公共请求方法
    public async request<T = any>(config: RequestConfig): Promise<T> {
      return this.instance.request(config)
    }
  
    // GET请求
    public get<T = any>(url: string, config?: RequestConfig): Promise<T> {
      return this.request({ method: 'GET', url, ...config })
    }
  
    // POST请求
    public post<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
      return this.request({ method: 'POST', url, data, ...config })
    }
  
    // PUT请求
    public put<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
      return this.request({ method: 'PUT', url, data, ...config })
    }
  
    // DELETE请求
    public delete<T = any>(url: string, config?: RequestConfig): Promise<T> {
      return this.request({ method: 'DELETE', url, ...config })
    }
  }
  
  // 创建实例（根据环境变量配置baseURL）
  const http = new HttpRequest(import.meta.env.VITE_API_BASE_URL)
  
  export default http
  